import os
import shutil
import pyzipper

def unzip_and_rename(zip_file_path, password):
    # 确保文件存在
    if not os.path.exists(zip_file_path):
        print(f"文件 {zip_file_path} 不存在")
        return None

    # 定义临时解压目录和最终存储目录
    temp_extract_dir = './files/tmp/'  # 临时解压目录
    final_extract_dir = './files/extracted/'  # 最终存储目录

    # 创建临时解压目录
    try:
        if not os.path.exists(temp_extract_dir):
            os.makedirs(temp_extract_dir)
    except Exception as e:
        print(f"创建临时解压目录失败: {e}")
        return None

    # 打开并解压加密的 zip 文件
    try:
        with pyzipper.AESZipFile(zip_file_path, 'r') as zip_ref:
            zip_ref.setpassword(password.encode('utf-8'))  # 设置解压密码
            zip_ref.extractall(temp_extract_dir)
            print(f"已解压文件到临时目录: {temp_extract_dir}")
    except RuntimeError as e:
        print(f"解压失败，请检查密码是否正确: {e}")
        return None

    # 获取解压后的文件夹名称
    try:
        dirs = os.listdir(temp_extract_dir)
        if len(dirs) != 1 or not os.path.isdir(os.path.join(temp_extract_dir, dirs[0])):
            print("解压后的目录结构不符合预期")
            return None
        original_folder_name = dirs[0]
        original_folder_path = os.path.join(temp_extract_dir, original_folder_name)
    except Exception as e:
        print(f"读取解压目录失败: {e}")
        return None



    # 查找并验证 .csv 文件
    try:
        csv_files = [f for f in os.listdir(original_folder_path) if f.endswith('.csv')]
        if len(csv_files) != 1:
            print("未找到或找到多个 .csv 文件")
            return None
        original_csv_name = csv_files[0]
        original_csv_path = os.path.join(original_folder_path, original_csv_name)
        print('111 original_folder_path = ', original_folder_path)
        print('111 original_csv_name = ', original_csv_name)
        print('111 original_csv_path = ', original_csv_path)

        # 提取需要的部分
        final_csv_name = original_csv_name.split('——')[0]  # 按照 "——" 分割，取第一部分
        print('222 final_csv_name = ', final_csv_name)

    except Exception as e:
        print(f"查找 .csv 文件失败: {e}")
        return None

    # 定义新的文件夹名和文件名
    new_folder_name = final_csv_name
    new_csv_name = f"{new_folder_name}.csv"

    # 最终存储路径
    print('333 - final_extract_dir = ', final_extract_dir)
    print('333 - new_folder_name = ', final_extract_dir)
    final_folder_path = os.path.join(final_extract_dir, new_folder_name)
    final_csv_path = os.path.join(final_folder_path, new_csv_name)

    # 如果目标文件夹已存在，则删除它
    try:
        if os.path.exists(final_folder_path):
            print(f"目标文件夹已存在，正在删除: {final_folder_path}")
            shutil.rmtree(final_folder_path)
    except Exception as e:
        print(f"删除目标文件夹失败: {e}")
        return None

    # 创建最终存储目录，并移动和重命名文件
    try:
        os.makedirs(final_folder_path, exist_ok=True)  # 创建最终存储目录
        shutil.move(original_csv_path, final_csv_path)  # 移动并重命名 .csv 文件
        print(f"已将文件移动到最终目录: {final_csv_path}")
    except Exception as e:
        print(f"文件移动失败: {e}")
        return None

    # 清理临时解压目录
    try:
        shutil.rmtree(temp_extract_dir)
        print(f"已清理临时解压目录: {temp_extract_dir}")
    except Exception as e:
        print(f"清理临时解压目录失败: {e}")

    print(f"已将文件夹重命名为: {new_folder_name}")
    print(f"已将文件重命名为: {new_csv_name}")

    return new_folder_name, new_csv_name


# 调用函数
zip_file_path = './files/weixin_bill_20250328.zip'
password = '017952'
result = unzip_and_rename(zip_file_path, password)

def unzip_and_parseJson(zip_file_path, password):
    # 解压并重命名文件夹和文件
    folder_name, csv_name = unzip_and_rename(zip_file_path, password)
    print(f"处理完成，文件夹名为：{folder_name}，文件名为：{csv_name}")

    if folder_name and csv_name:
        # 构建CSV文件路径
        csvFilePath = f'./files/extracted/{folder_name}/{folder_name}.csv'
        
    # 调用JSON转换功能
    try:
        from test import read_wechat_bill_csv, parse_wechat_bill
        import json

        raw_data = read_wechat_bill_csv(csvFilePath)
        json_data = parse_wechat_bill(raw_data)

        json_file_path = f'./files/extracted/{folder_name}/{folder_name}.json'

        with open(json_file_path, 'w', encoding='utf-8') as json_file:
            json.dump(json_data, json_file, ensure_ascii=False, indent=4)
        print(f"JSON 数据已成功保存到文件: {json_file_path}")
    except Exception as e:
        print(f"JSON转换失败: {str(e)}")

    csvFilePath = f'./files/extracted/{folder_name}/{folder_name}.csv'
    print(csvFilePath)

    return json_data

if __name__ == "__main__":
    result = unzip_and_parseJson(zip_file_path, password)
    # result = unzip_and_parseJson('./files/weixin_bill_20250328.zip', '575589')

# if result:
#     folder_name, csv_name = result
#     print(f"处理完成，文件夹名为：{folder_name}，文件名为：{csv_name}")

#     csvFilePath = f'./files/extracted/{folder_name}/{folder_name}.csv'
#     print(csvFilePath)

#     # 调用JSON转换功能
#     try:
#         from test import read_wechat_bill_csv, parse_wechat_bill
#         import json

#         raw_data = read_wechat_bill_csv(csvFilePath)
#         json_data = parse_wechat_bill(raw_data)

#         json_file_path = f'./files/extracted/{folder_name}/{folder_name}.json'

#         with open(json_file_path, 'w', encoding='utf-8') as json_file:
#             json.dump(json_data, json_file, ensure_ascii=False, indent=4)
#         print(f"JSON 数据已成功保存到文件: {json_file_path}")
#     except Exception as e:
#         print(f"JSON转换失败: {str(e)}")

#     csvFilePath = f'./files/extracted/{folder_name}/{folder_name}.csv'
#     print(csvFilePath)